<?php
/**
 * Description:
 * Author: hezhizheng
 * Date: 2018/11/15
 * Time: 9:57
 * Created by Created by Panxsoft.
 */

namespace App\Services\Customers\ResetPwd;

use App\Models\Customers\Customer;
use App\Services\Common\VerifyCodeService;
use App\Services\EasySms\EasySmsService;
use App\Services\Utils\ApiChecker;


class ResetPwdForTelephoneService
{
    use ApiChecker;
    private $customer;

    public function __construct()
    {
        $this->customer = new Customer;
    }


    /**
     * @param Customer $customer
     * @return array
     * @throws \Exception
     */
    public function resetPwd(Customer $customer)
    {
        $find_customer = $this->customer->where('telephone', $customer->telephone)
            ->where('dial_code', $customer->dial_code)
            ->first();
        $this->checkItemExist($find_customer);
        $this->checkIsTrue($find_customer->status === Customer::STATUS_ENABLE, trans('customer.disabled'));

        $new_pwd = Customer::randomDefaultPwd();

        $service = new VerifyCodeService;

        $cache_key = $service->getResetPwdCacheKey($customer->telephone, $customer->dial_code);

        // 验证验证码
        $service->checkVerifyCode($cache_key, $customer->verify_code);

        // 重置客户的密码为默认密码
        $update = $find_customer->update([
            'password' => bcrypt($new_pwd)
        ]);

        // 销毁验证码
        $service->destroyUsedVerifyCode($cache_key);

        // 在发一条短信把新密码发送到客户的手机号
        (new EasySmsService)->sendNewPassword($customer->telephone, $new_pwd, $customer->dial_code);

        if (config('app.debug')) {
            return compact('update', 'new_pwd');
        } else {
            return compact('update');
        }
    }
}